/**
 * 事务管理模块
 * 处理HTTP事务相关的业务逻辑
 */
export class TransactionsManager {
  constructor(dbCore) {
    this.db = dbCore;
    this.initStatements();
  }

  /**
   * 初始化预编译语句
   */
  initStatements() {
    // 保存请求的预编译语句
    this.saveRequestStmt = this.db.prepare(`
      INSERT OR REPLACE INTO requests 
      (id, url, method, headers, params, cookies, body, timestamp, httpVersion, clientHttpVersion, remoteHttpVersion, tlsVersion, clientIp, remoteIp)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);

    // 保存响应的预编译语句
    this.saveResponseStmt = this.db.prepare(`
      INSERT OR REPLACE INTO responses 
      (id, requestId, statusCode, headers, cookies, body, bodySize, timestamp, httpVersion, remoteHttpVersion, tlsVersion)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);

    // 保存事务记录的预编译语句
    this.saveTransactionStmt = this.db.prepare(`
      INSERT OR REPLACE INTO transactions 
      (id, requestId, responseId, duration, createdAt)
      VALUES (?, ?, ?, ?, ?)
    `);

    // 查询事务列表的预编译语句
    this.getTransactionsStmt = this.db.prepare(`
      SELECT 
        t.id,
        t.duration,
        t.createdAt,
        req.id as requestId,
        req.url,
        req.method,
        req.headers as requestHeaders,
        req.params,
        req.cookies as requestCookies,
        req.body as requestBody,
        req.timestamp as requestTimestamp,
        req.httpVersion as requestHttpVersion,
        req.clientHttpVersion,
        req.remoteHttpVersion,
        req.tlsVersion as requestTlsVersion,
        req.clientIp,
        req.remoteIp,
        res.id as responseId,
        res.statusCode,
        res.headers as responseHeaders,
        res.cookies as responseCookies,
        res.body as responseBody,
        res.bodySize,
        res.timestamp as responseTimestamp,
        res.httpVersion as responseHttpVersion,
        res.remoteHttpVersion as responseRemoteHttpVersion,
        res.tlsVersion as responseTlsVersion
      FROM transactions t
      LEFT JOIN requests req ON t.requestId = req.id
      LEFT JOIN responses res ON t.responseId = res.id
      ORDER BY t.createdAt DESC
      LIMIT ? OFFSET ?
    `);

    // 查询单个事务的预编译语句
    this.getTransactionStmt = this.db.prepare(`
      SELECT 
        t.id,
        t.duration,
        t.createdAt,
        req.id as requestId,
        req.url,
        req.method,
        req.headers as requestHeaders,
        req.params,
        req.cookies as requestCookies,
        req.body as requestBody,
        req.timestamp as requestTimestamp,
        req.httpVersion as requestHttpVersion,
        req.clientHttpVersion,
        req.remoteHttpVersion,
        req.tlsVersion as requestTlsVersion,
        req.clientIp,
        req.remoteIp,
        res.id as responseId,
        res.statusCode,
        res.headers as responseHeaders,
        res.cookies as responseCookies,
        res.body as responseBody,
        res.bodySize,
        res.timestamp as responseTimestamp,
        res.httpVersion as responseHttpVersion,
        res.remoteHttpVersion as responseRemoteHttpVersion,
        res.tlsVersion as responseTlsVersion
      FROM transactions t
      LEFT JOIN requests req ON t.requestId = req.id
      LEFT JOIN responses res ON t.responseId = res.id
      WHERE t.id = ?
    `);
  }

  /**
   * 保存完整的事务记录
   */
  saveTransaction(transaction) {
    try {
      const transactionDb = this.db.transaction(() => {
        // 保存请求
        this.saveRequestStmt.run(
          transaction.request.id,
          transaction.request.url,
          transaction.request.method,
          JSON.stringify(transaction.request.headers),
          JSON.stringify(transaction.request.params),
          JSON.stringify(transaction.request.cookies),
          transaction.request.body,
          transaction.request.timestamp,
          transaction.request.httpVersion || transaction.request.clientHttpVersion, // 向后兼容
          transaction.request.clientHttpVersion,
          transaction.request.remoteHttpVersion,
          transaction.request.tlsVersion,
          transaction.request.clientIp,
          transaction.request.remoteIp
        );

        // 保存响应（如果存在）
        let responseId = null;
        if (transaction.response) {
          responseId = transaction.response.id;
          this.saveResponseStmt.run(
            transaction.response.id,
            transaction.response.requestId,
            transaction.response.statusCode,
            JSON.stringify(transaction.response.headers),
            JSON.stringify(transaction.response.cookies),
            transaction.response.body,
            transaction.response.bodySize,
            transaction.response.timestamp,
            transaction.response.httpVersion || transaction.response.remoteHttpVersion, // 向后兼容
            transaction.response.remoteHttpVersion,
            transaction.response.tlsVersion
          );
        }

        // 保存事务记录
        this.saveTransactionStmt.run(
          transaction.id,
          transaction.request.id,
          responseId,
          transaction.duration,
          transaction.createdAt
        );
      });

      transactionDb();
      return true;
    } catch (error) {
      console.error('❌ 保存事务失败:', error.message);
      return false;
    }
  }

  /**
   * 获取事务列表
   */
  getTransactions(limit = 100, offset = 0) {
    try {
      const rows = this.getTransactionsStmt.all(limit, offset);
      return rows.map(this.transformRowToTransaction.bind(this));
    } catch (error) {
      console.error('❌ 获取事务列表失败:', error.message);
      return [];
    }
  }

  /**
   * 获取单个事务
   */
  getTransaction(id) {
    try {
      const row = this.getTransactionStmt.get(id);
      if (!row) {
        return null;
      }
      return this.transformRowToTransaction(row);
    } catch (error) {
      console.error('❌ 获取事务失败:', error.message);
      return null;
    }
  }

  /**
   * 将数据库行转换为事务对象
   */
  transformRowToTransaction(row) {
    const transaction = {
      id: row.id,
      duration: row.duration,
      createdAt: row.createdAt,
      request: {
        id: row.requestId,
        url: row.url,
        method: row.method,
        headers: this.safeJsonParse(row.requestHeaders, {}),
        params: this.safeJsonParse(row.params, {}),
        cookies: this.safeJsonParse(row.requestCookies, {}),
        body: row.requestBody,
        timestamp: row.requestTimestamp,
        httpVersion: row.requestHttpVersion,
        clientHttpVersion: row.clientHttpVersion,
        remoteHttpVersion: row.remoteHttpVersion,
        tlsVersion: row.requestTlsVersion,
        clientIp: row.clientIp,
        remoteIp: row.remoteIp
      }
    };

    // 添加响应数据（如果存在）
    if (row.responseId) {
      transaction.response = {
        id: row.responseId,
        requestId: row.requestId,
        statusCode: row.statusCode,
        headers: this.safeJsonParse(row.responseHeaders, {}),
        cookies: this.safeJsonParse(row.responseCookies, {}),
        body: row.responseBody,
        bodySize: row.bodySize,
        timestamp: row.responseTimestamp,
        httpVersion: row.responseHttpVersion,
        remoteHttpVersion: row.responseRemoteHttpVersion,
        tlsVersion: row.responseTlsVersion
      };
    }

    return transaction;
  }

  /**
   * 安全的JSON解析
   */
  safeJsonParse(jsonString, defaultValue = null) {
    try {
      return jsonString ? JSON.parse(jsonString) : defaultValue;
    } catch (error) {
      console.warn('⚠️ JSON解析失败:', error.message);
      return defaultValue;
    }
  }

  /**
   * 清空所有事务记录
   */
  clearAllTransactions() {
    try {
      const clearTransaction = this.db.transaction(() => {
        this.db.exec('DELETE FROM transactions');
        this.db.exec('DELETE FROM responses');
        this.db.exec('DELETE FROM requests');
      });

      clearTransaction();
      console.log('📚 已清空所有事务记录');
      return true;
    } catch (error) {
      console.error('❌ 清空事务记录失败:', error.message);
      return false;
    }
  }

  /**
   * 获取事务统计信息
   */
  getTransactionStats() {
    try {
      const stats = {};

      // 总事务数
      const totalCount = this.db.prepare('SELECT COUNT(*) as count FROM transactions').get();
      stats.totalTransactions = totalCount.count;

      // 今天的事务数
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const todayCount = this.db.prepare(`
        SELECT COUNT(*) as count FROM transactions 
        WHERE createdAt >= ?
      `).get(today.getTime());
      stats.todayTransactions = todayCount.count;

      // 按方法统计
      const methodStats = this.db.prepare(`
        SELECT req.method, COUNT(*) as count
        FROM transactions t
        JOIN requests req ON t.requestId = req.id
        GROUP BY req.method
        ORDER BY count DESC
      `).all();
      stats.byMethod = methodStats;

      // 按状态码统计
      const statusStats = this.db.prepare(`
        SELECT res.statusCode, COUNT(*) as count
        FROM transactions t
        JOIN responses res ON t.responseId = res.id
        WHERE res.statusCode IS NOT NULL
        GROUP BY res.statusCode
        ORDER BY count DESC
      `).all();
      stats.byStatusCode = statusStats;

      // 平均响应时间
      const avgDuration = this.db.prepare(`
        SELECT AVG(duration) as avgDuration
        FROM transactions
        WHERE duration IS NOT NULL
      `).get();
      stats.averageDuration = avgDuration.avgDuration || 0;

      return stats;
    } catch (error) {
      console.error('❌ 获取事务统计失败:', error.message);
      return {};
    }
  }

  /**
   * 删除指定时间之前的事务
   */
  cleanupOldTransactions(daysToKeep = 30) {
    try {
      const cutoffTime = Date.now() - (daysToKeep * 24 * 60 * 60 * 1000);
      
      const cleanupTransaction = this.db.transaction(() => {
        // 获取要删除的事务ID
        const transactionsToDelete = this.db.prepare(`
          SELECT id, requestId, responseId FROM transactions 
          WHERE createdAt < ?
        `).all(cutoffTime);

        if (transactionsToDelete.length === 0) {
          return { deleted: 0 };
        }

        // 删除事务记录
        const deleteTransactions = this.db.prepare('DELETE FROM transactions WHERE createdAt < ?');
        deleteTransactions.run(cutoffTime);

        // 删除孤立的请求记录
        const deleteOrphanRequests = this.db.prepare(`
          DELETE FROM requests 
          WHERE id NOT IN (SELECT requestId FROM transactions WHERE requestId IS NOT NULL)
        `);
        deleteOrphanRequests.run();

        // 删除孤立的响应记录
        const deleteOrphanResponses = this.db.prepare(`
          DELETE FROM responses 
          WHERE id NOT IN (SELECT responseId FROM transactions WHERE responseId IS NOT NULL)
        `);
        deleteOrphanResponses.run();

        return { deleted: transactionsToDelete.length };
      });

      const result = cleanupTransaction();
      console.log(`📚 已清理 ${result.deleted} 条旧事务记录`);
      return result;
    } catch (error) {
      console.error('❌ 清理旧事务失败:', error.message);
      return { deleted: 0, error: error.message };
    }
  }
} 